import { Injectable, UnauthorizedException } from '@nestjs/common';
import { TokenCreateDto } from '../dto/TokenCreateDto';
import { UserService } from './UserService';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { FindUserType } from 'src/constants';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async createToken(tokenCreateRequest: TokenCreateDto): Promise<string> {
    // 查看当前用户是否存在数据库
    const user = await this.userService.findByName(
      tokenCreateRequest.username,
      FindUserType.Find,
    );

    if (!user) {
      throw new UnauthorizedException('用户名或密码错误');
    }
    // 比对密码
    // const match = await bcrypt.compare(
    //   tokenCreateRequest.password,
    //   user.encrytedPassword,
    // ); // 注意修正了拼写错误

    // if (!match) {
    //   throw new UnauthorizedException('用户名或密码错误');
    // }

    // 生成令牌并且返回
    const payload = {
      sub: user.id,
      username: user.username,
      // 可以在此添加更多需要的信息
    };
    const token = await this.jwtService.signAsync(payload);
    return token;
  }
}
